import moment from 'moment';
import React from 'react';
import { formatMessage } from 'umi';

const toType = (key) => {
  const map = {
    uppercase: {
      text: formatMessage({ id: '大写字母' }),
      regexp: /[A-Z]+/,
    },
    lowercase: {
      text: formatMessage({ id: '小写字母' }),
      regexp: /[a-z]+/,
    },
    specialRequired: {
      text: formatMessage({ id: '特殊符号' }),
      regexp: new RegExp(
        "[`\\+\\-~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]",
      ),
    },
    numericRequired: {
      text: formatMessage({ id: '数字' }),
      regexp: /[0-9]+/,
    },
  };
  return map[key];
};

export const validatePassword = (value = '', rule) => {
  const { minLength = 6, maxLength = 16, typeKeys = [] } = rule;

  const requiredTypes = typeKeys.map((item) => toType(item)).filter((item) => item);

  if (
    value.length >= minLength &&
    value.length <= maxLength &&
    requiredTypes.every((item) => item.regexp.test(value))
  ) {
    return {
      result: true,
      message: '',
    };
  }

  return {
    result: false,
    message: formatMessage(
      { id: '密码不合规提示' },
      {
        minLength,
        maxLength,
        strRequiredTypes: requiredTypes.map((item) => item.text).join('、'),
      },
    ),
  };
};

//---------------------------------------------------------------------------

/**
 * 0 修正
 * 0 => 00, 7 => 07, 13 => 13
 */
export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

/**
 * 时间间隔
 * today => 2019-01-11 00:00:00, 2019-01-11 23:59:59
 * week => 2019-01-07 00:00:00, 2019-01-13 23:59:59
 * month => 2019-01-01 00:00:00, 2019-01-31 23:59:59
 * year => 2019-01-01 00:00:00, 2019-12-31 23:59:59
 */
export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

//----------------------------------------------------------------------

/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

//----------------------------------------------------------------------

export function formatWan(val) {
  const v = val * 1;
  if (!v) return '';

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
        <span
          style={{
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            marginLeft: 2,
          }}
        >
          万
        </span>
      </span>
    );
  }
  return result;
}

export const importCDN = (url, name) =>
  new Promise((resolve) => {
    const dom = document.createElement('script');
    dom.src = url;
    dom.type = 'text/javascript';
    dom.onload = () => {
      resolve(window[name]);
    };
    document.head.appendChild(dom);
  });
